<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>axios基本使用</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
  </head>
  <body>
    <button>点击发送 GET 请求</button>
    <button>点击发送 GET 请求2</button>
    <button>点击发送 POST 请求</button>
    <button>点击发送 PUT 请求</button>
    <button>点击发送 PATCH 请求</button>
    <button>点击发送 DELETE 请求</button>

    <script>
      const buttons = document.querySelectorAll('button')
    
      //get请求
      buttons[0].onclick = ()=>{
        axios({
            method:'GET',
            
            url:'http://localhost:3000/movie/2',
            
            params:{ //自动转换query参数
              id:2,
              name:'大话西游'
            }
        }).then(
          response=>{ // 成功的value为response对象,data属性保存的是解析好js对象
            console.log(response.data);
          }
        ),error=>{
          console.log(error);
          alert(error.message)
        }
      }


      buttons[1].onclick = async()=>{
      try{
        const response = await axios({
            method:'GET',
            
            url:'http://localhost:3000/movie',
            
            params:{ //自动转换query参数
              id:2,
              name:'大话西游'
            }
          })
        }catch(error){
          console.log(error);
          alert(error.message)
        }
      }

      // 添加
      buttons[2].onclick = async()=>{
        const response = await axios({
            method:'post',
            
            url:'http://localhost:3000/movie',
            
            data:'name=荒野求生&director=贝爷'
             
          })
          console.log(response.data);
      }

      // 更新
      buttons[3].onclick = async()=>{
        const response = await axios({
            method:'put',
            
            url:'http://localhost:3000/movie/6',
            
            // data:'name=荒野求生&director=贝爷'

            data:{ //自动转换Json
              name:'荒野求生1',
              director:'贝爷2'
            }
             
          })
          console.log(response.data);
      }

       // 更新
       buttons[5].onclick = async()=>{
        const response = await axios({
            method:'delete',
            
            url:'http://localhost:3000/movie/8',
          
          })
          console.log(response.data);
      }
    </script>
  </body>
</html>
